/**
 * @author caif
 * @fileoverview fileView
 */
App.Views.itemView = Backbone.View.extend({
	
	className : "doc-item list-item",
	
	initialize : function() {
		var self = this;
		self.listenTo(self.model, 'renaming', self.edit);
        self.listenTo(self.model, 'change:name', self.updateNameHandler);
        self.listenTo(self.model, 'update-detail-panel', self.updateDetailPanel);
	},
    
    updateNameHandler: function(model){
        var self = this;
        $.ajax({
        	type: 'put',
            url: window._global.contextPath + "/file.json",
            data: {
            	operate:'rename',
                name: model.get('name'),
                id: model.get('id')
            },
            error: function(xhr){
                model.set({name: model.previous('name')}, {silent: true});
                self.render();
            },
            success: function(data){
            	//change left menu if it exist
                var id = App.util.removePrefixOfId(model.get('id'));
                var projectModel = App.viewInstances.appView.getProjectItemModelById(id);
                if(projectModel){
                    projectModel.set({'name': model.get('name')});
                }
            }
        });
    },
    
	clear: function() {
	    this.model.clear();
	},
	
	toggleDone : function(e){
		var self = this,
		docList = App.viewInstances.appView.docList,
		allItems =  docList.children(),
	    highlightItems = docList.find('.highlight');
		if(e.shiftKey){
			//shift selection function
	 	     var lastClicked = docList.find('.last-clicked');
			 if(lastClicked.length > 0){
			 	var lastClickedIndex = allItems.index(lastClicked),
			    clickedIndex = allItems.index(self.$el),
			    startIndex = 0,
			    endIndex = 0;
			    startIndex = Math.min(lastClickedIndex, clickedIndex);
			    endIndex = Math.max(lastClickedIndex, clickedIndex);
		        for(var i = 0, l = allItems.length; i <= l; i++){
		            if(i < startIndex || i > endIndex){
		                allItems.eq(i).removeClass('highlight');
		            }else{
		                allItems.eq(i).addClass('highlight');
		            }
		        }
			    return false;
			 }
		}
	    if( !e.ctrlKey && !e.metaKey ){
		    highlightItems.removeClass("highlight");
	    }else{
	    	App.viewInstances.appView.contextMenu.hide();
	    }
	    highlightItems.removeClass('last-clicked');
	    self.$el.toggleClass("highlight").addClass('last-clicked');
	    return false;
	},
	
	edit: function(e){
		var self = this;
		self.$el.addClass("editing");
		self.input.select();
	},
	
	cancelEdit: function(e){
		this.$el.removeClass("editing");
		this.input.val(this.model.get("name")).trigger('blur');
	},
	
	stop : function(e){
	    e.stopPropagation();
	},

	updateOnEnter: function(e){
		if (e.which === 13){
			this.close();
		} else if(e.which === 27){
			//esc, cancel eidt
			this.cancelEdit(e);
			return false;
		}
	},
	
	getLocaleDate : function(val){
	    return App.util.getLocaleDate(val);
	},

	getSize : function(val){
		if(this.model.get('revisionNumber') === 0) return App.i18n.get('unknown');
        return App.util.formatSize(val);
	},
	/**
     * @description process databag 
     * @param databagId 
     * @param extension
     * @param jsonObj
     * @param template
    */
	processDatabag : function( databagId , extension , jsonObj ,template){
	     var that = this,
	     extension = extension.toLowerCase();
	     jsonObj.databagURL = window._global.databagURL;
	     if( extension =="jpg" || extension =="bmp" || extension =="jpeg" || extension =="gif" || extension =="png" )
	     {
	         jsonObj.processImage = true;
	         jsonObj.href = window.location.href;
	         that.$el.html( Mustache.to_html(template, jsonObj)); 
	     }
	     else
	     {
	         $.ajax({
             url :  App.util.contextPath +"/bag/"+ databagId +"/progress",
             success : function(rep){
	                 if( parseInt(rep) == -1 )
	                 {
	                     jsonObj.processFail = true;
	                 }
	                 else if( parseInt(rep) < 100)
	                 {
	                     jsonObj.processing = true;
	                 }
	                 else if( parseInt(rep) == 100 )
	                 {
	                     jsonObj.processDone = true;
	                     jsonObj.href = window.location.href;
	                 }
	                 that.$el.html( Mustache.to_html(template, jsonObj)); 
	                 that.$el.find(".updateTime").text( that.getLocaleDate(parseInt(that.$el.find(".updateTime").text())).toLocaleString());
	                 that.input = that.$('.common_edit');
	             }
	             ,
	          error : function(){
	             jsonObj.processFail = true;
	             that.$el.html( Mustache.to_html(template, jsonObj)); 
                 that.$el.find(".updateTime").text( that.getLocaleDate(parseInt(that.$el.find(".updateTime").text())).toLocaleString());
                 that.input = that.$('.common_edit');
	          }
	         }
	         
	         );
	     }
	 },
	 
	 deleteRevision: function(del){
		var self = this;
		App.util.showTip(App.i18n.get('isDeletingRevision'));
		$.ajax({
            url : window._global.contextPath + "/revision/"+del.attr("id")+".json",
            type : "delete",
//            data : {id:this.model.get("id"),revision:del.attr("revision")},
            success : function(){
            	self.updateDetailPanel(function(model){
            		self.model.set(model.file);
            	});
        	}
        });
	 },
	
	updateDetailPanel: function(callback){
		var self = this;
		App.util.showTip(App.i18n.get('isRetrievingDetail'));
		var location = window.location.href;
		$.ajax({
            url : "detail.json?id=" + this.model.get("id"),
            async : false,
            success : function( model ){
            	App.util.hideTip();
                App.util.updateModel(model.file);
                var modelObj = model.file;
                modelObj.location = location;
                modelObj.databagURL = window._global.databagURL;
                if(modelObj.revisions.length == 1){
                	modelObj.del = true;
                }
                else
                {
                	modelObj.del = false;
                }
                for( var i = 0 ; i< modelObj.revisions.length ; i++){
                    modelObj.revisions[i].fileSize = self.getSize( modelObj.revisions[i].fileSize );
                    modelObj.revisions[i].timestamp = self.getLocaleDate(parseInt( modelObj.revisions[i].timestamp ));
                }
                var type= model.file.extension.toLowerCase();
                if( type == "rvt" || type=="doc" || type=="docx" || type=="xls" || type=="xlsx" ||
                    type=="ppt" || type=="pptx" || type=="txt" || type=="pdf" || type == "dwg"){
                    $.ajax({
                        url : App.util.contextPath +"/bag/"+ modelObj.dataBagId +"/progress",
                        async : false,
                        success : function( response ){
                            if( parseInt(response) == 100)
        	                {
        	                     modelObj.progress = true;
        	                     modelObj.btn = true;
        	                }
        	                else if( parseInt(response) < 100 )
        	                {
        	                    modelObj.progress = false;
        	                    modelObj.btn = false;
        	                }
        	                $("#bottom-detail-content").html( Mustache.to_html( tpl.detail , modelObj ))
        	                .find(".del-btn").click(function() {
         	                	self.deleteRevision($(this));
         	                	return false;
							});
                        }
                    });
                }else if( type == "jpg" || type=="png" || type=="gif" || type=="jpeg" || type=="bmp" ){
                    modelObj.btn = true;
                    modelObj.progress = true;
                }
                $("#bottom-detail-content").html( Mustache.to_html( tpl.detail , modelObj ))
                .find(".del-btn").click(function() {
                	self.deleteRevision($(this));
                	return false;
				});
                callback && callback(model);
            }
        });
		$("#activity-content").empty();
		$.ajax({
			url : App.util.contextPath + "/activity.json?receiverId=" + this.model.get("id"),
			async : false,
			success : function( model ){
				for( var i=0 ; i< model.items.length ; i++ )
				{
					$("#activity-content").append(model.items[i].displayContent);
				}
			}
		});
		$(".version-row").hover(function(e){
        	$(e.currentTarget).find(".detail-btn").show();
        },function(e){
        	$(e.currentTarget).find(".detail-btn").hide();
        });
	},
	
	close : function(e){
		var self = this,
        value = $.trim(self.input.val());
        self.model.set('name', value);
        self.$el.removeClass("editing");
    },
    
    open: function(e){
        //this.$el.find(".folder_label a")[0].click();
        //todo: above will trigger click event(call `updateDetail` function)
    	if(App.viewInstances.appView.currentFilter.fromRecycle) return;
        if($(e.target).is(':input')) return;
        window.location.hash = this.$el.find("label a").attr('href');
    },
     
    updateDetail : function(e){
        var self = this;
        //drag and drop: prevent click event while drop
        //jquery ui has a bug on draggable element: see http://bugs.jqueryui.com/ticket/4261
        if(self.$el.hasClass('no-click-evt') || $(e.target).is(':input')) return;
        //manually trigger input's blur event
        var input = $('#document_list .highlight input');
        if(input.length > 0){
            input[0].blur();
        }
        self.toggleDone(e);
        if(!self.model.get("folder") && App.viewInstances.appView.isDetailPanelShown()) {
            self.updateDetailPanel();
        }else{
            App.viewInstances.appView.hideDetailPanel();
        }
        App.viewInstances.appView.updateHeaderBtn( self.model );
    }
});
